#ifndef _UTIL_HPP
#define _UTIL_HPP

#include <sys/socket.h>
#include "Log.hpp"

class Util 
{
  public:
    /*
     *  分隔符
     *  \n
     *  \r
     *  \r\n
     *  根据平台
     */
    static int ReadLine(int sock, std::string& out)
    {
        char ch = 'Y';
        while(ch != '\n')
        {
           ssize_t s = recv(sock, &ch, sizeof(ch), 0); 
           if(s == 1)
           {
              if(ch == '\r')
              {
                  // MSG_PEEK：窥视功能，只读不取出来
                  recv(sock, &ch, sizeof(ch), MSG_PEEK);
                  if(ch != '\n')
                  {
                      ch = '\n';
                  }
                  else
                  {
                      // 取出'\n'
                      recv(sock, &ch, sizeof(ch), 0);
                  }
              }

              out += ch;
           }
           else if(s == 0)
           {
              LOG(WARNING, "对端关闭连接!"); 
              return 0;
           }
           else
           {
              return -1;
           }
        }
        return out.size();
    }

    static bool CutString(const std::string& target, std::string& sub1_out, std::string& sub2_out, std::string sep)
    {
       size_t pos = target.find(sep);
       if(pos != std::string::npos)
       {
            // 切割字符串AAAA: BBBB
            sub1_out = target.substr(0, pos); // [)
            sub2_out = target.substr(pos + sep.size()); // 直接切完
            return true;
       }
       else return false;
    }
};


#endif
